/*************************************************************************
  > File Name: acct_OS X ver.c
  > Author: Angel Criss
  > Mail: abbytsing@gmail.com 
  > Created Time: 一  7/14 15:22:16 2014
 ************************************************************************/
// acct and acc_view
// on OS X man acct and man 5 acct
#include<errno.h>
#include<stdio.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/acct.h>

void err(char *func)
{
    perror(func);
    _exit(errno);
}

int main(int argc,char *argv[])
{
    struct acct ac;
    int acct_file,numRead;

    if(argc<3)
    {
	    if(getuid()!=0)
	    {
		    printf("run as root while %s filename[on]/NULL[disable]\n",argv[0]);
		    exit(EXIT_SUCCESS);
        }
		if(acct(argv[1])==-1)
               err("acct");
		printf("acct is %s\n",(argv[1]==NULL)?"disable":"on");
        exit(EXIT_SUCCESS); // won't report segmentfault anymore :)

    }

    if(strcmp(argv[1],"-v")==0)
    {
        if(argc<3)
        {
    		printf("%s -v filename[view]",argv[0]);
            exit(EXIT_SUCCESS);
        }
    
        if((acct_file=open(argv[2],O_RDONLY))==-1)
            err("open");
        printf("\e[42muid\t\t\tcommand\t\t\tmemery\e[0m\n");
        while((numRead=read(acct_file,&ac,sizeof(struct acct)))>0)
        {
            if(numRead!=sizeof(struct acct))
                err("read");
            printf("%-8d\t\t%-8s\t\t%-8d\n",ac.ac_uid,ac.ac_comm,ac.ac_mem);
            /*由于ac_comm[10],所以进程名大于10会被截断*/
        }
    }
}
